<template>
    <div class="file-item bg-white p-4 my-2 rounded-lg flex items-stretch ">
        <div>

        </div>
        <div class="flex flex-col flex-auto justify-between">
            <div class="mb-2">
                <div class="font-medium mr-3 text-gray-600 leading-tight">
                    {{upload.file.name}}
                </div>
                <div class="text-sm">
                    {{ sizeDisplay }} MB
                </div>
            </div>
            <div class="text-gray-600 text-sm">
                <template v-if="state === states.WATIING">等待上传</template>
                <template v-if="state === states.UNSUPPORTED">不支持此分类文件</template>
            </div>
        </div>
        <div class="file-preview flex items-end justify-end">
            <img :src="tmp" alt="" class="w-16 h-16">
        </div>
    </div>
</template>

<script>
    import states from "@/uploader/state.js"
    export default {
        props: {
            upload:{
                require: true,
                type: Object
            },
            baseURI:{
                require: true,
                type: String,
            },
            endpoint:{
                require: true
            }
        },
        data(){
            return {
                tmp: '',
                state: null,
                states
            }
        },
        computed:{
            sizeDisplay(){
                return (this.upload.file.size / (1024 * 1024)).toFixed(2)
            }
        },
        mounted(){
            this.handlePreviewLoad(this.upload.file)
            if(this.endpoint === null){
                return this.state = states.UNSUPPORTED;
            }
            this.state = states.WATIING;
        },
        methods:{
            picFileResult(result){
                result.then((r) => {
                    this.tmp = r
                })
                return this.tmp;
            },
            async handlePreviewLoad(upload){
                if (!upload.type.match('image')) {
                    return false
                }
                var picReader = new FileReader();
                 this.picFileResult(new Promise((resolve, reject) => {
                    picReader.addEventListener('load',  (e) => {
                        let result = e.target.result
                        resolve(result)
                    })
                    picReader.readAsDataURL(upload);
              }));
            }

        }
    }
</script>
